package com.wjs.juc.CAS;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * cas之手写自旋锁
 */
public class SpinLockDemo {
    AtomicReference<Thread> atomicReference=new AtomicReference<>();

    /**
     * 加锁方法
     */
    public void lock(){
        Thread thread = Thread.currentThread();
        System.out.println(thread.getName()+"come in");
        while (!atomicReference.compareAndSet(null,thread)){

        }
    }

    /**
     * 解锁方法
     */
    public void unlock(){
        Thread thread = Thread.currentThread();
        atomicReference.compareAndSet(thread,null);
        System.out.println(thread.getName()+"task over");
    }
    public static void main(String[] args) throws InterruptedException {
        SpinLockDemo lock = new SpinLockDemo();
        new Thread(()->{
            lock.lock();
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            lock.unlock();
        },"t1").start();

        TimeUnit.SECONDS.sleep(1);

        new Thread(()->{
            lock.lock();
            lock.unlock();
        },"t2").start();
    }
}
